package com.hqq.leetcode.dp;

import com.hqq.exercise.tree.TreeNode;

/**
 * MaxPathSum 二叉树中的最大路径和
 * Description:
 * Given a binary tree, find the maximum path sum.
 * The path may start and end at any node in the tree.
 * Input:
 * ---1
 * -/ \
 * 2   3
 * Output:
 * 6
 * <p>
 * Created by heqianqian on 2017/9/17.
 */
public class MaxPathSum {

    private int max = Integer.MIN_VALUE;

    public static void main(String[] args) {
        /*DATA PREPARATION*/
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);

        MaxPathSum mps = new MaxPathSum();
        int maxSum = mps.maxPathSum(root);
        System.out.println(maxSum);
    }

    /*
     * @param root: The root of binary tree.
     * @return: An integer
     */
    public int maxPathSum(TreeNode root) {
        // write your code here
        helper(root);
        return max;
    }

    private int helper(TreeNode root) {
        if (root == null) {
            return 0;
        }
        //左子树节点和的最大值
        int left = helper(root.left);
        //右子树节点和的最大值
        int right = helper(root.right);
        //比较左右子树哪个到节点的和最大
        int currSum = Math.max(Math.max(left + root.val, right + root.val), root.val);
        //是否过节点值会更大
        int currMax = Math.max(currSum, left + right + root.val);
        max = Math.max(currMax, max);
        return currSum;
    }

}
